<template>
  <!-- 只有商品名称存在的时候才会渲染，解决商品价格闪烁为undifined的问题 -->
  <view v-if="goods_info.goods_name" class="goods-detail-container">
    <!-- 轮播图区域 -->
    <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
      <swiper-item v-for="(item,i) in goods_info.pics" :key="i">
        <image :src="item.pics_big" @click="preview(i)"></image>
      </swiper-item>
    </swiper>
    
    <!-- 商品信息区域 -->
    <view class="goods-info-box">
      <!-- 商品价格 -->
      <view class="price">￥{{goods_info.goods_price}}</view>
      <!-- 商品主体区域 -->
      <view class="goods-info-body">
        <!-- 商品名字 -->
        <view class="goods-name">{{goods_info.goods_name}}</view>
        <!-- 收藏 -->
        <view class="collection">          
        <uni-icons type="star" size="18" color="gray" @click="collectClickHandler(goods_info)" v-if="!itemIsCollected"></uni-icons>
          <uni-icons type="star-filled" size="18" color="gray" v-else @click="collectClickHandler(goods_info)"></uni-icons >
          <text>收藏</text>
        </view>
      </view>
      
      <!-- 运费区域 -->
      <view class="diliverFee">快递：免运费
      </view>
      
      <!-- 商品导航组件区域 -->
      <view class="goods_nav">
          <!-- fill 控制右侧按钮的样式 -->
          <!-- options 左侧按钮的配置项 -->
          <!-- buttonGroup 右侧按钮的配置项 -->
          <!-- click 左侧按钮的点击事件处理函数 -->
          <!-- buttonClick 右侧按钮的点击事件处理函数 -->
          <uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick" @buttonClick="buttonClick" />
      </view>
    </view>
  
    <!-- 点击立即购买/加入购物车后的弹窗 -->
    <uni-popup ref="popup" type="bottom">
      
      <!-- 整个弹窗 -->
      <view class="sizes">
        <!-- 遮罩 -->
        <view class="sizes-mask show"></view>
        <!-- 主体 -->
        <view class="sizes-pop none">
          <!-- 关闭 -->
          <view class="sizes-pop-close"></view>
          
          <!-- 弹窗头部 -->
          <view class="sizes-pop-head">
            <!-- 图片 -->
            <view class="sizes-pop-head-img">
              <image mode="widthFix" :src="goods_info.goods_small_logo"></image>
            </view>
            
            <!-- 图片右侧的信息 -->
            <view class="sizes-pop-head-text">
              <view class="sizes-pop-head-text-name">{{goods_info.goods_name}}</view>
              <view class="sizes-pop-head-text-price"><label>￥</label><text>{{price}}</text></view>
              <view class="sizes-pop-head-text-left">剩余{{stock}}份</view>
            </view>
          </view>
            
            <!-- 主要的规格选择 -->
            <scroll-view scroll-y class="sizes-pop-main">
              <!-- 先循环出所有规格 -->
              <view class="sizes-pop-main-list" v-for="(item,i1) in sizes" :key="i1">
                <view class="sizes-pop-main-list-name">{{item.name}}</view>
                <!-- 第二层循环 -->
                <view class="sizes-pop-main-list-item">
                  <text :class="item.start === i2?'selected':''" v-for="(item2,i2) in item.children" :key="i2" @click="change(i1,i2)">{{item2.title}}</text>
                </view>
              </view>
              
            </scroll-view>
            
            <!-- 数量 -->
            <view class="sizes-pop-number">
              <view class="sizes-pop-number-text">数量</view>
              <view class="number">
                    <uni-number-box :min="1" :value="1" @change="numChangeHandler"></uni-number-box>
              </view>
            </view>
            
            <!-- 放入购物车 -->
            <view class="sizes-pop-bottom" v-if="true">
              <label @click="addToCartHandler" v-if="bottom_button_click">加入购物车</label>
              <label @click="payHandler" v-else>立即购买</label>
            </view>
             

          </view>
          
      </view>
      
    </uni-popup>
  </view>
</template>

<script>
  
  import { mapState,mapMutations,mapGetters } from 'vuex'

  
  export default {
    computed:{
      // 调用mapState方法，把m_cart模块中的cart数组映射到当前页面中作为计算属性使用
      ...mapState('m_cart',['cart']),
      ...mapGetters('m_cart',['total']),
      ...mapState('m_collection',['collection','itemIsCollected'])
      
      
    },
    
    // 定义watch监听器,当total值变化时调用方法
    watch:{
      // total(newVal){
      //   const isCart = this.options.find(x => x.text === '购物车')
      //   if(isCart){
      //     isCart.info = newVal
      //   }
      // }
      
      // 上面的写法有个问题，页面首次加载完毕后不会调用监听器，因为total没有变化，所以把total写为一个对象
      total:{
        handler(newVal){
            const isCart = this.options.find(x => x.text === '购物车')
            if(isCart){
              isCart.info = newVal
            }
        },
        // 当页面一加载就调用
        immediate:true
      }
    },
    
    data() {
      return {
        goods_info:{},
        // 左侧按钮组的配置对象
            options: [{
              icon: 'cart',
              text: '购物车',
              info: 0
            }],
            // 右侧按钮组的配置对象
            buttonGroup: [{
                text: '加入购物车',
                backgroundColor: '#ff0000',
                color: '#fff'
              },
              {
                text: '立即购买',
                backgroundColor: '#ffa200',
                color: '#fff'
              }
            ],
            
            
            // 弹窗参数
            // 货物价格
            price: 0,
            
            // 货物剩余数量
            stock: 0,
            
            // 选定的货物规格id
            sizes_detail_id:0,
            
            // 用户在numberbox中选择的数量，默认为1
            count: 1,
            
            // 选定的规格,存的是键值对,useChooseSize是在本页中的规格键值对，userChooseSizes是用于保存的键值对
            userChooseSize: {},
            
            // 判断多规格商品的Boolean值
            goods_have_sizes:true,
            
            // 用于判断是显示加入购物车还是立即购买，true为加入购物车,false为立即购买
            bottom_button_click:true,
            
            
            // 多规格商品的规格
            sizes: [{
                sizes_id: 0,
                name: '规格',
                // start是选中的内容
                start: 0,
                children: [{
                    children_id: 102,
                    title: '小份'
                  },
                  {
                    children_id: 103,
                    title: '中份'
                  }
                ]
              },
              {
                sizes_id: 1,
                name: '口味',
                // start是选中的内容
                start: 0,
                children: [{
                    children_id: 102,
                    title: '甜味'
                  },
                  {
                    children_id: 103,
                    title: '烧烤味'
                  }
                ]
              },
            ],
            
            // 商品的规格细节
            sizes_detail: [{
                'id': '1',
                'price': '3999',
                'stock': '10',
                'productSpecs': {
                  '规格': '小份',
                  '口味': '甜味'
                }
              },
              {
                'id': '2',
                'price': '4999',
                'stock': '20',
                'productSpecs': {
                  '规格': '小份',
                  '口味': '烧烤味'
                }
              },
              {
                'id': '3',
                'price': '5999',
                'stock': '30',
                'productSpecs': {
                  '规格': '中份',
                  '口味': '甜味'
                }
              },
              {
                'id': '4',
                'price': '6999',
                'stock': '40',
                'productSpecs': {
                  '规格': '中份',
                  '口味': '烧烤味'
                }
              }
            ],
            

      };
    },
    
    onLoad(options){
      const goods_id = options.goods_id
      this.getGoodsDetail(goods_id)
    
    },
    
    methods:{
      // 用mapMutations将模块中的addToCart方法映射过来
      ...mapMutations('m_cart',['addToCart','updateAllGoodsState','updateGoodsState','updateGoodsCount']),
      ...mapMutations('m_collection',['collectClickHandler','updateCollectionState','changeValue','isCollected']),
      ...mapMutations('m_order',['updateUserChooseSizes']),
      
      
      async getGoodsDetail(goods_id){
        const {data:res} = await uni.$http.get('/api/public/v1/goods/detail',{goods_id:goods_id})
        if(res.meta.status != 200) return uni.$showMsg()
        
        this.goods_info = res.message
    
        
        // // 没有后端先没收藏，后面删掉
        // this.goods_info.goods_state_collected = false
        
        // // 改变itemIsCollected的值
        // this.changeValue(this.goods_info.goods_state_collected)
        // 判断本地储存的收藏中是否有该物品并改变值
          this.isCollected(goods_id)
      },
      
      // 预览图片
      preview(i){
        uni.previewImage({
          current:i,
          // map函数找元素生成新数组
          urls:this.goods_info.pics.map(x => x.pics_big)
        })
      },
      
      onClick(e){
        uni.switchTab({
          url:'/pages/cart/cart'
        })
      },
      
      // 商品详情页面右下角两个按钮
      async buttonClick(e){
        // console.log(e)
        
        // 点击加入购物车
        if(e.content.text === '加入购物车'){
          this.bottom_button_click = true;
          
          // 默认值为所有规格的第一个
          const length = this.sizes.length
          for(let i = 0;i < length;i++){
            this.saveToUserChooseSize(i,0)
          }
         
         // 打开弹窗
          this.$refs.popup.open()

        }
        
        // 点击立即购买
        if(e.content.text === '立即购买'){
          this.bottom_button_click = false
          
          // 默认值为所有规格的第一个
           const length = this.sizes.length
           for(let i = 0;i < length;i++){
             this.saveToUserChooseSize(i,0)
           }
          
          // 打开弹窗
           this.$refs.popup.open()
          
          }
        },
        
        // 改变选定规格样式
        change(i1, i2) {
          this.sizes[i1].start = i2
        
          // 将选中的选项存起来放入userChooseSize键值对中
          this.saveToUserChooseSize(i1, i2)
        
        },
        
        
        //将选中的选项存起来放入userChooseSize键值对中
        saveToUserChooseSize(i1, i2) {
          this.userChooseSize[this.sizes[i1].name] = this.sizes[i1].children[i2].title
          
          // 将userChooseSize储存
          this.updateUserChooseSizes(this.userChooseSize)
        
          // console.log(this.userChooseSize)
        
          // 将键值对与传过来的进行比较
          this.sizes_detail.forEach(item => {
            if (this.isObjectValueEqualNew(this.userChooseSize, item.productSpecs)) {
              // 设置金额,数量和规格id
              this.price = item.price
              this.stock = item.stock
              this.sizes_detail_id = item.id
        
            }
          })
        },
        
        
        // 弹窗中点击加入购物车
        addToCartHandler(){
            // 创建商品对象
            //商品的属性有goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state_checked
            const goods = {
              goods_id:this.goods_info.goods_id,
              goods_name:this.goods_info.goods_name,
              goods_price:this.price - 0,
              goods_count:this.count,
              goods_small_logo:this.goods_info.goods_small_logo,
              // 是否选中
              goods_state_checked:true,
              goods_sizes:this.userChooseSize,
              goods_sizes_detail_id:this.sizes_detail_id - 0,
            }
            
            // 将商品对象加入购物车
            this.addToCart(goods)
            
            this.$refs.popup.close()
            
            uni.$showMsg('加入购物车成功!')
            
        },
        
        // 弹窗中点击立即购买
        payHandler(){
          
          // goods_count先定为1
            uni.navigateTo({
              url:'/subpkg/order_confirm/order_confirm?' + 
              'goods_id=' + this.goods_info.goods_id + '&' +
              'goods_count=' + this.count 

            })
        },
        

        // 用户选择的物品数量改变
        numChangeHandler(val) {
          this.count = val
        
        },
        

        // 判断键值对是否相等的函数
        isObjectValueEqualNew(a, b) {
          // 判断对象是否指向同一内存
          if (a === b) return true;
        
          // 获取对象键值数组
          let aProps = Object.getOwnPropertyNames(a);
          let bProps = Object.getOwnPropertyNames(b);
        
          // 判断键值数组长度是否一致
          if (aProps.length !== bProps.length) return false;
        
          // 遍历键值
          for (let prop in a) {
            // 判断a的键是否在b中存在
            if (b.hasOwnProperty(prop)) {
              // 存在则判断a的键值是否为对象
              if (typeof a[prop] === 'object') {
                // 是对象则判断是否相等
                // 如果不相等
                if (!isObjectValueEqual(a[prop], b[prop])) return false;
              } else if (a[prop] !== b[prop]) {
                return false;
              }
            }
            // a的键在b中不存在
            else {
              return false;
            }
          }
        
          return true;
        },
        
        // 点击收藏
        itemAddToCollection(e){
          this.addToCollection(e)
        },
        

        

      }
    }
    
    
  
</script>

<style lang="scss">
swiper{
  height: 750rpx;
  
  image{
    width: 100%;
    height:100%;
    
  }
}

  
.goods-info-box{
  padding:10px;
  padding-right:0;
  
  .price{
    color:#c00000;
    font-size:18px;
    margin:10px 0;
  }
  
  .goods-info-body{
    display: flex;
    // 两端贴边对齐
    justify-content: space-between;
    
    .goods-name{
      font-size: 13px;
      margin-right: 10px;
    }
    .collection{
      width: 120px;
      font-size: 12px;
      display: flex;
      flex-direction: column;
      align-items: center;
      border-left: 1px solid #efefef;
      color:gray;
    }
  }
  
  .diliverFee{
    font-size: 12px;
    color:gray;
    margin:10px 0;
  }
}

.goods_nav{
  position: fixed;
  bottom: 0;
  left: 0;
  width:100%;
}

.goods-detail-container{
  // 防止遮住导航区域
  padding-bottom: 50px;
}

.sizes {
    width: 100%;
    height: 100%;
    position: fixed;
    bottom: 0px;
    left: 0px;
    z-index: 999;

    .sizes-mask {
      width: 100%;
      height: auto;
      position: fixed;
      top: 0px;
      bottom: 0px;
      left: 0px;
      right: 0px;
      margin: 0px auto;
      background: rgba(0, 0, 0, 0.4);
      z-index: 1000;
    }

    .sizes-pop {
      width: 100%;
      height: auto;
      position: fixed;
      bottom: 0px;
      left: 0px;
      right: 0px;
      z-index: 1001;
      background: #fff;
      border-radius: 5px 5px 0px 0px;

      .sizes-pop-close {}

      .sizes-pop-head {
        width: 94%;
        height: auto;
        margin: 0px auto;
        border-bottom: 1px #eee solid;
        display: flex;
        flex-direction: row;
        padding: 20rpx 0px;

        .sizes-pop-head-img {
          width: 25%;

          image {
            width: 100%;
            height: 200rpx;
            border: 1px #eee solid;
            display: block;
          }
        }


        .sizes-pop-head-text {
          width: 75%;
          display: flex;
          flex-direction: column;
          box-sizing: border-box;
          padding-left: 3%;
          justify-content: space-around;

          .sizes-pop-head-text-name {
            font-size: 16px;
            font-weight: bold;
            width: 90%;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            color: #444;
          }

          .sizes-pop-head-text-price {
            display: flex;
            flex-direction: row;
            color: #eaa02c;
            display: table-cell;

            vertical-align:bottom label {
              font-size: 12px;
              font-weight: bold;
              margin-right: 2%;
            }

            text {
              font-size: 18px;
            }
          }

          .sizes-pop-head-text-left {
            font-size: 13px;
            color: #888;
            margin-right: 3%;
          }
        }
      }

      .sizes-pop-main {
        width: 100%;
        max-height: 600rpx;
        padding-top: 10px;

        .sizes-pop-main-list {
          width: 100%;
          height: auto;
          box-sizing: border-box;
          padding: 0px 3%;
        }

        .sizes-pop-main-list-name {
          width: 100%;
          height: auto;
          font-size: 15px;
          color: #333;
          margin-bottom: 15px;
        }

        .sizes-pop-main-list-item {
          width: 100%;
          height: auto;
          display: flex;
          flex-direction: row;
          flex-wrap: wrap;

          text {
            color: #fe7b2e;
            margin: 0px 0%;
            border-radius: 4px;
            text-align: center;
            box-sizing: border-box;
            min-width: 30%;
            border: 1px #fe7b2e solid;
            margin-bottom: 15px;
            font-size: 14px;
            line-height: 33px;
            padding: 0px 2%;
            margin-right: 3%;
          }
        }
      }

      .sizes-pop-number {
        width: 100%;
        height: auto;
        box-sizing: border-box;
        padding: 40rpx 5%;
        display: flex;
        justify-content: space-between;
      }

      .sizes-pop-bottom {
        width: 100%;
        height: auto;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 10px 3%;
        box-sizing: border-box;
        border-top: 1px #eee solid;

        label {
          text-align: center;
          color: #fff;
          height: 100rpx;
          line-height: 100rpx;
          /* background-image:linear-gradient(#ff4f19,#E33E33); */
          background: #E31D1A;
          border-radius: 40px;
          letter-spacing: 3px;
        }
      }
    }
  }

  .selected {
    background: #ff8d00;
    color: #fff !important;
  }
</style>
